import axios from 'axios';
import qs from 'qs'
import {Message, Loading} from 'element-ui';
import {log} from '@/utils/LogKit';

const $axios = axios.create({
    baseURL: "http://localhost:9001",
    timeout: 5000,
});

let loading: any;   //定义loading变量
function startLoading() {
    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoading() {    //使用Element loading-close 方法
    loading.close()
}

// 请求拦截  设置统一header
$axios.interceptors.request.use(config => {
    // 加载
    startLoading();
    let token = localStorage.getItem("x-auth-token");
    config.headers.token = "token 111111111111111111";
    // config.baseURL = "http://127.0.0.1:9001";
    log("转换之前data", config.data)
    config.data = qs.stringify(config.data)
    log("url", config.url)
    log("params", config.params)
    log("转换之后data", config.data)
    config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    config.headers.Authorization = "Authorization222222222222222222";
    return config
}, error => {
    return Promise.reject(error)
});

// 响应拦截  401 token过期处理
$axios.interceptors.response.use(response => {
    console.log(response);
    endLoading();
    let data = response.data;
    if (data.code == 200) {

    }
    if (data.code == 401) {
    }
    if (data.code == 500) {
    }
    return data as any

}, error => {
    // 错误提醒
    endLoading();
    Message.error(error.response.data);
    const {status} = error.response;
    if (status == 401) {
        Message.error('token值无效，请重新登录');
        // 清除token
        localStorage.removeItem('eleToken');
        // 页面跳转
        // router.push('/login')
    }
    return Promise.reject(error)
});

export default $axios




